import pyautogui
import pyperclip
import os
import time

pyautogui.PAUSE = 0.5


# 在当前屏幕找到图片位置并点击
def mapping_img(img):
    image_l = pyautogui.locateOnScreen(
        img, grayscale=True
    )  # 获取在当前屏幕的图片的位置
    if img == "微信搜索框.png":
        center = pyautogui.center(image_l)
        pyautogui.click(center)
        pyautogui.click(center)  # 这里是调试时发现搜索框点击一次点不上，又加了一行
    else:
        center = pyautogui.center(image_l)
        pyautogui.click(center)


# 在聊天搜索框输入昵称搜索聊天对象打开和他的对话框
def chat_user(user):
    if user != "":
        pyperclip.copy(user)
        mapping_img("微信搜索框.png")
        pyautogui.hotkey("ctrl", "v")
        # pyautogui.press('enter')
        time.sleep(1)
        pyautogui.moveRel(xOffset=0, yOffset=80)
        pyautogui.click()
        time.sleep(2)


# 点击微信窗口的上传文件按钮输入要发送的文件地址并打开，加载到待发送消息框
def readfile(filename):
    pyperclip.copy(filename)
    mapping_img("微信上传文件.png")  # 点击微信窗口的“上传文件”按钮
    time.sleep(1)
    pyautogui.hotkey("ctrl", "v")
    pyautogui.press("enter")


def main():
    os.chdir("C:\\Users\\Administrator\\微信图片")
    # 切换路径，微信搜索框和上传文件图片都在此路径
    for dirpath, dirnames, filenames in os.walk(
        "C:\\Users\\Administrator\\Desktop\\总监区数据", topdown=False
    ):
        for name in filenames:
            user_name = name.split("总监")[0]
            path1 = os.path.join(dirpath, name)
            if user_name.find("+") != -1:
                for i in range(user_name.count("+")):
                    user1 = user_name.split("+")[i]
                    chat_user(user1)
                    readfile(path1)
                    pyautogui.press("enter")
                    pyperclip.copy("这是程序测试发出的文件，不用理会")
                    pyautogui.hotkey("ctrl", "v")
                    pyautogui.press("enter")
            else:
                chat_user(user_name)
                readfile(path1)
                pyautogui.press("enter")
                pyperclip.copy("这是程序测试发出的文件，不用理会")
                pyautogui.hotkey("ctrl", "v")
                pyautogui.press("enter")


if __name__ == "__main__":
    main()
